<?php

/**
 * 公共函数库.
 * 
 * @author aic <41262633@qq.com>
 */

/**
 * Class Common.
 */
class Common {

    /**
     * 404 not found.
     * 
     * @param string $message 提示信息.
     * @param string $returnUrl 跳转网址.
     * 
     * @return void
     */
    public static function noPage($message = '', $returnUrl = '') {
        header('HTTP/1.1 404 Not Found');
        header('status: 404 Not Found');

        require TPL_PATH . 'notice.html';
        exit;
    }

    /**
     * 页面错误
     */
    public static function error($message = '') {
        require TPL_PATH . 'notice.html';
        exit;
    }

    /**
     * ajax输出.
     * 
     * @param mixed $input 输入参数.
     * 
     * @return void
     */
    public static function ajaxOut($input) {
        die(json_encode($input));
    }

    /**
     * ajax返回正确.
     * 
     * @param string $message 提示信息.
     * @param array $data 附加的数据.
     * 
     * @return void
     */
    public static function ajaxReturnSuccess($message = '', $data = array()) {
        $return = array(
            'error' => 0,
            'message' => $message,
            'data' => $data,
        );
        static::ajaxOut($return);
    }

    /**
     * ajax返回失败.
     * 
     * @param string $message 提示信息.
     * 
     * @return void
     */
    public static function ajaxReturnFalse($message = '') {
        $return = array(
            'error' => 1,
            'message' => $message,
        );
        static::ajaxOut($return);
    }

    /**
     * 错误提示.
     * 
     * @param string $message 错误提示信息.
     * 
     * @return void
     */
    public static function showErrorMsg($message = '') {
        if (static::isAjaxRequest()) {
            static::ajaxReturnFalse($message);
        } else {
            static::noPage($message);
        }
    }

    /**
     * 判断是否是post提交操作.
     * 
     * @return boolean.
     */
    public static function isPost() {
        return isset($_SERVER["REQUEST_METHOD"]) && $_SERVER["REQUEST_METHOD"] === 'POST' ? true : false;
    }

    /**
     * 判断是否是ajax请求.
     * 
     * @return boolean.
     */
    public static function isAjaxRequest() {
        return isset($_SERVER['HTTP_X_REQUESTED_WITH']) && $_SERVER['HTTP_X_REQUESTED_WITH'] === 'XMLHttpRequest' ? true : false;
    }

    /**
     * 页面跳转.
     * 
     * @param string $url 页面跳转url.
     * 
     * @return void
     */
    public static function redirect($url) {
        header("Location: $url");
        // 跳转的后续代码, 强制终止.
        exit(0);
    }

    /**
     * 数组以某个键值为索引返回.
     * 
     * @param array $arr 原始数组值.
     * @param string $key 返回数组索引键.
     * 
     * @return array.
     */
    public static function getArrByKey($arr = array(), $key = '') {
        $return = array();
        foreach ($arr as $a) {
            if (isset($a[$key])) {
                $return[$a[$key]] = $a;
            } else {
                $return[] = $a;
            }
        }
        return $return;
    }

    /**
     * 判断是否是移动设备.
     * 
     * @return boolean.
     */
    public static function isMob() {
        return preg_match("/(android|avantgo|blackberry|bolt|boost|cricket|docomo|fone|hiptop|mini|mobi|palm|phone|pie|tablet|up\.browser|up\.link|webos|wos)/i", $_SERVER["HTTP_USER_AGENT"]);
    }

    /**
     * 判断是否微信客户端浏览
     */
    public static function isWx() {
        $agent = strtolower($_SERVER['HTTP_USER_AGENT']);
        return strpos($agent, 'micromessenger') === false ? 0 : 1;
    }

    /**
     * 获取短链接
     */
    public static function getShortUrl($url = '', $try_times = 0) {

        if ($try_times > \Config\System::$site['trytimes']) {
            return '';
        }

        $getUrl = \Config\System::$site['wbShortUrl'] . $url;
        $shortUrl = '';

        $result = file_get_contents($getUrl);
        $tmp = json_decode($result, true);
        if ($tmp && isset($tmp['urls']) && isset($tmp['urls'][0])) {
            $shortUrl = $tmp['urls'][0]['url_short'];
        }

        if (!$shortUrl) {
            $try_times++;
            return self::getShortUrl($url, $try_times);
        }

        return $shortUrl;
    }

    /**
     * 获取二维码链接
     */
    public static function getQrcode($url = '') {
        return \Config\System::$site['qqQrcode'] . $url;
    }

    /**
     * 数据压缩
     */
    public static function deflate_data($data) {
        if (empty($data)) {
            return '';
        }

        $output = json_encode($data);
        return rtrim(strtr(base64_encode(gzdeflate($output, 9)), '+/', '-_'), '=');
    }

    /**
     * 数据解压
     */
    public static function inflate_data($data) {
        if (empty($data)) {
            return '';
        }
        return json_decode(gzinflate(base64_decode(strtr($data, '-_', '+/'))), true);
    }

    /**
     * 对月销量进行格式化
     */
    public static function format_volume($volume = 0) {
        if ($volume < 10000) {
            return $volume;
        }

        $w = sprintf("%01.1f", $volume / 10000);

        if (intval($w) == $w) {
            $w = intval($w);
        }

        return $w . '万';
    }

    /**
     * 获取省钱字符串
     */
    public static function getShengString($amout = 0, $red_packet = 0) {
        $string = [];
        if ($amout > 0) {
            $string[] = '券' . $amout;
        }

        if ($red_packet > 0) {
            $string[] = '收货红包' . $red_packet;
        }

        if ($string) {
            return implode('+', $string) . ', <span class="red">省' . ($amout + $red_packet) . '元</span>';
        } else {
            return '';
        }
    }

    /**
     * 获取随机的字符串
     */
    public static function randomStr($key = '') {
        $key = $key . microtime(true);
        return hash('crc32b', $key); // crc32b 快于crc32.
    }

    /**
     * 订单加密
     */
    public static function pwdOrderId($order_id = '') {
        $substr = substr($order_id, -14, 12);
        $return = str_replace($substr, '************', $order_id);
        return $return;
    }

    /**
     * 图片base64编码
     */
    public static function base64Img($imgsrc = '') {
        if (!$imgsrc) {
            return '';
        }

        $content = file_get_contents($imgsrc);
        if (!$content) {
            return '';
        }

        return 'data:image/jpg;base64,' . base64_encode($content);
    }

    /**
     * 设置cookie.
     * 
     * @param string $key 设置的cookie key.
     * @param mixed $value 保存到cookie中的值.
     * @param integer $expireTime cookie有效时间.
     * @param string $path 生效的目录.
     * 
     * @return void
     */
    public static function setCookie($key, $value, $expireTime = 7200, $path = '/') {
        setcookie($key, $value, time() + $expireTime, $path, "", false, true);
    }

    /**
     * 获取cookie.
     * 
     * @param string $key 获取的cookie key.
     * @param boolean $filterData 是否过滤数据.
     * 
     * @return mixed.
     */
    public static function getCookie($key = '', $filterData = true) {
        $value = isset($_COOKIE[$key]) ? trim($_COOKIE[$key]) : '';
        return $filterData ? self::filterData($value) : $value;
    }

    /**
     * 格式化与过滤数据.
     * 
     * @param mixed $data 待过滤的数据.
     * 
     * @return mixed.
     */
    public static function filterData($data) {
        if (!$data) {
            return $data;
        }

        if (is_array($data)) {
            // 递归处理数组.
            foreach ($data as $k => $v) {
                $data[$k] = self::filterData($v);
            }
        } else {
            // 过滤两边空格.
            $data = trim($data);
            // 过滤html标签.
            $data = strip_tags($data, '<a><div><p><img>');
            // 使用反斜线引用字符串.
            $data = addslashes($data);
        }

        return $data;
    }

}
